package com.small.site.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.Ordered;

/**
 * @author  xiaochi
 * @date    2021/11/21 13:38
 * @desc    自定义全局基础过滤器
 */
@Slf4j
public abstract class BaseGlobalFilter implements GlobalFilter, Ordered, ApplicationContextAware {

    protected static ApplicationContext ctx;

    @Override
    @SuppressWarnings("all")
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        log.info("GatewayGlobalFilter.setApplicationContext，ctx={}",applicationContext);
        BaseGlobalFilter.ctx = applicationContext;
    }

    /**
     * 返回json
     * @param response
     * @param message
     * @return
     */
    protected Mono<Void> responseJson(ServerHttpResponse response,Object message){
        return response.writeWith(Mono.fromSupplier(() -> {
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return response.bufferFactory().wrap(JSON.toJSONString(message).getBytes());
        }));
    }
}
